package controllers;
import business.CustomerInfo;
import business.SysUser;
import com.shove.Convert;
import controllers.BaseController;
import models.*;
import org.apache.axis.server.ParamList;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.db.jpa.JPA;
import play.server.Server;
import utils.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 后台登录, 增删改 统一用 ajax, 查用 回发
 */
public class BackendCenter extends BaseController {
    public static void orderList(String pay_status,String startTime,String endTime,String username) {
        StringBuilder sql = new StringBuilder();
        StringBuilder sqlCount = new StringBuilder();
        String sqlAppend = " where 1=1 ";
        sys_user sysUser = SysUser.getSessionUser();
        if(!StringUtils.isEmpty(pay_status)){
            sqlAppend += " and  pay_status=" + pay_status;
        }
        if(!sysUser.username.equals("admin")){
            sqlAppend += " and business_id =  " + sysUser.id + " ";
        }
        if(!StringUtils.isEmpty(startTime)){
            sqlAppend +="  and buy_date > '"+startTime+"' ";
        }
        if(!StringUtils.isEmpty(endTime)){
            sqlAppend +="  and buy_date < '"+endTime+"' ";
        }
        if(!StringUtils.isEmpty(username)){
            sqlAppend += " and customer_name like '%"+username+"%' ";
        }
        sql.append(" select * from customer_info ")
                .append(sqlAppend) // 搜索条件
                .append(" order by id desc ");//order by
        sqlCount.append(" select count(*) from customer_info ").append(sqlAppend);
        PageBean<customer_info> pageBean = CustomerInfo.select(sql,sqlCount,params);
        render(pageBean,startTime,endTime,username,pay_status);
    }
    public static void orderImport(String v){
        if("show".equals(v)){
            render();
        }else if("export".equals(v) && SysUser.isAdmin()){// 是管理员才能全部导出
            String[] rowsName = new String[]{"客户姓名","烫画图片","下单时间","价格","张数","金额","付款状态","客户级别","客户来源"};
            List<customer_info>  dataList = customer_info.findAll();
            List<Object[]>  dataListCopy = new ArrayList<>();
            Object[] objs = null;
            for (int i = 0; i < dataList.size(); i++) {
                objs = new Object[rowsName.length];
                customer_info customerInfo = dataList.get(i);
                objs[0] = customerInfo.customer_name;
                objs[1] = customerInfo.filename;
                objs[2] = customerInfo.getBuy_date();
                objs[3] = customerInfo.getSingle_price();
                objs[4] = customerInfo.all_count+"";
                objs[5] = customerInfo.getSum_price();
                objs[6] = customerInfo.getPay_status();
                objs[7] = customerInfo.customer_level;
                objs[8] = customerInfo.customer_source;
                dataListCopy.add(objs);
            }
            ExportExcel ex = new ExportExcel("sheet1", rowsName, dataListCopy);
            try {
                ex.export(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            renderText("非法操作0613");
        }
    }
    //工序组编辑 add 添加动作，edit 修改动作，默认查看
    public static void orderEdit(){
        ErrorInfo errorInfo = new ErrorInfo();
        customer_info item;
        String v = params.get("v");
        if(Constants.postAddKey.equals(v) || Constants.postUpdateKey.equals(v)){
            errorInfo = CustomerInfo.add(params);
            renderJSON(errorInfo);
        }else if(Constants.viewUpdateKey.equals(v)){
            item = customer_info.findById(Long.parseLong(params.get("id")));
            render(item);
        }else if(Constants.viewAddKey.equals(v)){
            render();
        }else if(Constants.postDeleteKey.equals(v)){
            String[] strs=params.get("ids").split(",");
            for(int i=0;i<strs.length;i++){
                long id = Convert.strToLong(strs[i],0);
                if(id>0){
                    customer_info customerInfo = customer_info.findById(id);
                    FileUtil.deleteFile(customerInfo.filename);
                    customer_info.delete("from customer_info where id=?",id);
                }
            }
            errorInfo.msg="删除成功";
            errorInfo.code=1;
            renderJSON(errorInfo);
        }else if("show".equals(v)){
            item = customer_info.findById(Long.parseLong(params.get("id")));
            render("/BackendCenter/orderShow.html",item);
        }else if("importExcel".equals(v)){
            String filename = params.get("filename");
            String abpath = Constants.getAbsPath();
            String absolutePath = abpath + Constants.abspath + filename;
            InputStream is;
            try {
                is = new FileInputStream(absolutePath);
                List<String> filenameList = new ArrayList<>();//把图片的文件名放到filenameList 里面
                List<models.CustomerInfo> customerInfoList = ExcelUtils.getList(is,true,filenameList);
                //根据文件路径
                for (int i = 0; i < customerInfoList.size(); i++) {
                    models.CustomerInfo cBean = customerInfoList.get(i);
                    customer_info customerInfo = new customer_info();
                    customerInfo.business_id = SysUser.getSessionUser().getId();
                    customerInfo.customer_name = cBean.客户姓名;
                    customerInfo.buy_date = cBean.下单时间;
                    customerInfo.single_price = cBean.价格;
                    customerInfo.all_count = cBean.张数;
                    customerInfo.sum_price = cBean.金额;
                    customerInfo.pay_status = cBean.getPayStatus();
                    customerInfo.customer_level = cBean.客户级别;
                    customerInfo.customer_source = cBean.客户来源;
                    customerInfo.create_date = new Date();
                    customerInfo.filename = cBean.烫画图片;
                    customerInfo.save();
                }
                errorInfo.msg="数据成功导入 " + customerInfoList.size() + "条";
                FileUtil.deleteFile(filename);//导入数据成功后删除这个没用的文件
            } catch (Exception e) {
                e.printStackTrace();
            }
            errorInfo.code=1;
            renderJSON(errorInfo);
        }
        renderText("error access");
    }
    //订单量统计
    public static void orderStatistic(String pay_status,String startTime){
        //2018-05 ~ 2018-06
        if(StringUtils.isEmpty(startTime)){
            Date date = new Date();
            Date date2 = DateUtil.dateAddMonth(date,1);
            startTime = Convert.dateToStr(date,"yyyy-MM","")+" ~ " + Convert.dateToStr(date2,"yyyy-MM","");
        }
        String[] str0 = startTime.split("~");
        String[] str1 = str0[0].split("-");
        String[] str2 = str0[1].split("-");
        int y1 = Integer.parseInt(str1[0].trim());
        int m1= Integer.parseInt(str1[1].trim());
        int y2=Integer.parseInt(str2[0].trim());
        int m2=Integer.parseInt(str2[1].trim());
        String where = "";
        String where2 = "";
        long currId = SysUser.getSessionUser().getId();
        if(!StringUtils.isEmpty(pay_status)){
            where = " and a.pay_status =" + pay_status ;
        }
        if(!SysUser.isAdmin()){
            where2 += " where b.id ="+ currId +" ";
            where += " and a.business_id=" + currId + " " ;
        }else{
            where2 += " where b.id = a.business_id ";
        }
        String sql = "select DATE_FORMAT(a.buy_date,'%Y') as y, DATE_FORMAT(a.buy_date,'%m') as m,sum(a.all_count) as all_acount,sum(a.sum_price) as sum_price," +
                "(select b.username from sys_user b  "+where2+") as name from customer_info a " +
                " where DATE_FORMAT(a.buy_date,'%Y') >=?1   and DATE_FORMAT(a.buy_date,'%Y')<=?2 and DATE_FORMAT(a.buy_date,'%m') >=?3 and DATE_FORMAT(a.buy_date,'%m') <=?4 " + where +
                " group by a.business_id order by DATE_FORMAT(a.buy_date,'%Y') , DATE_FORMAT(a.buy_date,'%m')  ";
        List<Object[]> list = JPA.em().createNativeQuery(sql)
                .setParameter(1,y1)
                .setParameter(2,y2).setParameter(3,m1).setParameter(4,m2).getResultList();
//        Logger.info("list.size()=" + list.size() + "y1=" + y1 + ",m1=" + m1 + ",y2="+y2+",m2="+m2+"]" + sql);
        render(pay_status,startTime,list);
    }
}
